package me.jessyan.armscomponent.app.mvp.ui.util;

import static com.jess.arms.utils.ArmsUtils.mToast;

import android.app.Activity;
import android.app.Application;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.jess.arms.integration.AppManager;
import com.jess.arms.utils.ArmsUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.UUID;

import me.jessyan.armscomponent.app.mvp.ui.adapter.DeviceInfoArrayAdapter;
import me.jessyan.armscomponent.app.mvp.ui.model.DeviceInformation;
import me.jessyan.armscomponent.commonres.dialog.ProgresDialog;

public class BlueToothUtil {
    private String TAG = "BlueToothUtil";
    public static final int REQUEST_BLUETOOTH_SCAN_RESULT = 1000;
    public static final int PERMISSION_REQUEST_CONSTANT = 1;
    private BluetoothAdapter mBluetoothAdapter;
    private BroadcastReceiver mBluetoothReceiver;//用于接收蓝牙状态改变广播的广播接收者
    private BroadcastReceiver mBLuetoothStateReceiver;
    private BluetoothDevice mDevice;
    private BluetoothSocket mBluetoothSocket;
    private final UUID mUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//蓝牙串口服务的UUID
    private static OutputStream mOS;

    private static BlueToothUtil instance;
    private Context mContext;
    private ToastUtil mToast;
    public static BlueToothUtil getInstance(Context context){
        synchronized (BlueToothUtil.class){
            if(instance == null){
                instance = new BlueToothUtil(context);
            }
        }
        return instance;
    }

    public BlueToothUtil(Context context){
        this.mContext = context;
        mToast = new ToastUtil(mContext);
    }


    public static boolean checkBlueToothIsEnable() {
        return BluetoothAdapter.getDefaultAdapter().isEnabled();
    }

    public static boolean switchBlueToothIsEnable() {
        if(BluetoothAdapter.getDefaultAdapter().isEnabled()){
            BluetoothAdapter.getDefaultAdapter().disable();
        }else {
            BluetoothAdapter.getDefaultAdapter().enable();
        }
        return BluetoothAdapter.getDefaultAdapter().isEnabled();
    }

    /**
     * 注册广播接收者
     */
    public void initReceiver(List<DeviceInformation> mDatas, DeviceInfoArrayAdapter mAdapter) {
        //创建用于接收蓝牙状态改变广播的广播接收者
        mBLuetoothStateReceiver = new BroadcastReceiver(){
            @Override
            public void onReceive(Context context, Intent intent) {
                int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
                switch (state){
                    case BluetoothAdapter.STATE_ON:
                        mToast.showToast("蓝牙已打开");
                        break;
                    case BluetoothAdapter.STATE_OFF:
                        mToast.showToast("蓝牙已关闭");
                        break;
                    case BluetoothAdapter.STATE_TURNING_ON:
                        mToast.showToast("蓝牙正在打开");
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        mToast.showToast("蓝牙正在关闭");
                        break;
                }
            }
        };
        //创建设备扫描广播接收者
        mBluetoothReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                    boolean isAdded = false;//标记扫描到的设备是否已经在数据列表里了
                    //获取扫描到的设备
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    //保存设备的信息
                    DeviceInformation deviceInformation = new DeviceInformation(device.getName(),device.getAddress());
                    for (DeviceInformation data : mDatas) {
                        //判断已保存的设备信息里是否有一样的
                        if (data.getDeviceAddress().equals(deviceInformation.getDeviceAddress())) {
                            isAdded = true;
                            break;
                        }
                    }
                    if (!isAdded) {
                        //通知UI更新
                        mDatas.add(deviceInformation);
                        mAdapter.notifyDataSetChanged();
                    }
                }
            }
        };
        //注册广播接收者
        IntentFilter filter1 = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_FOUND);

        mContext.registerReceiver(mBLuetoothStateReceiver,filter1);
        mContext.registerReceiver(mBluetoothReceiver,filter2);
    }

    /**
     * 权限是否授予，给出提示
     */
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CONSTANT: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mToast.showToast("权限授权成功");
                }else{
                    mToast.showToast("权限授权失败");
                }
                return;
            }
        }
    }

    /**
     * 检测和开启蓝牙
     */
    public void openBluetooth() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter != null) {
            //判断蓝牙是否打开并可见
            if (!mBluetoothAdapter.isEnabled()) {
                //请求打开并可见
                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                ((Activity)mContext).startActivityForResult(intent,PERMISSION_REQUEST_CONSTANT);
            }
        }else{
            mToast.showToast("设备不支持蓝牙功能");
        }
    }

    /**
     * 搜索蓝牙设备
     */
    public void discoverBluetooth(){
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        //搜索设备
        mBluetoothAdapter.startDiscovery();
        mToast.showToast("正在搜索设备");
    }

    /**
     * 停止扫描
     */
    public void cancelBluetooth(){
        if (mBluetoothAdapter.isDiscovering()) {
            //停止搜索设备
            mBluetoothAdapter.cancelDiscovery();
        }
    }

    /**
     * 与目标设备建立连接
     */
    public void connectDevice(String mAddress) {
        DialogUtil.getInstants(AppManager.getAppManager().getCurrentActivity()).showProgressDialog();
        //获取默认蓝牙设配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //通过地址拿到该蓝牙设备device
        mDevice = mBluetoothAdapter.getRemoteDevice(mAddress);
        try {
            // 连接建立之前的先配对
            if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
                Method creMethod = BluetoothDevice.class
                        .getMethod("createBond");
                Log.e("TAG", "开始配对");
                creMethod.invoke(mDevice);
            }
            //建立socket通信
            mBluetoothSocket = mDevice.createRfcommSocketToServiceRecord(mUUID);
            mBluetoothSocket.connect();
            if (mBluetoothSocket.isConnected()) {
                DialogUtil.getInstants(AppManager.getAppManager().getCurrentActivity()).hideProgressDialog();
                mToast.showToast("连接成功");
                //开启接收数据的线程
                ReceiveDataThread thread = new ReceiveDataThread();
                thread.start();
            }else{
                DialogUtil.getInstants(AppManager.getAppManager().getCurrentActivity()).hideProgressDialog();
                mToast.showToast("连接失败，结束重进");
            }
        } catch (IOException e) {
            e.printStackTrace();
            DialogUtil.getInstants(AppManager.getAppManager().getCurrentActivity()).hideProgressDialog();
            mToast.showToast("连接出错！ ");
            try {
                mBluetoothSocket.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        } catch (Throwable e) {
            DialogUtil.getInstants(AppManager.getAppManager().getCurrentActivity()).hideProgressDialog();
            e.printStackTrace();
        }
    }

    /**
     * 发送数据的方法
     * @param contentStr
     */
    public void sendMessage(String contentStr) {
        if (mBluetoothSocket.isConnected()) {
            try {
                //获取输出流
                mOS = mBluetoothSocket.getOutputStream();
                if (mOS != null) {
                    //写数据（参数为byte数组）
                    mOS.write(contentStr.getBytes("GBK"));
                    mToast.showToast("发送成功");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            mToast.showToast("没有设备已连接");
        }
    }

    public void destroyConnected(){
        try {
            if(mBluetoothSocket != null && mBluetoothAdapter != null) {
                if (mBluetoothSocket.isConnected()) {
                    //关闭socket
                    mBluetoothSocket.close();
                    mBluetoothAdapter = null;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 负责接收数据的线程
     */
    public class ReceiveDataThread extends Thread{

        private InputStream inputStream;

        public ReceiveDataThread() {
            super();
            try {
                //获取连接socket的输入流
                inputStream = mBluetoothSocket.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void run() {
            super.run();
            int len = 0;
            byte[] buffer = new byte[256];
            while (true){
                try {
                    inputStream.read(buffer);
                    for (byte b : buffer) {
                        Log.d(TAG,"b:" + b);
                    }
                    //设置GBK格式可以获取到中文信息，不回乱码
                    String a = new String(buffer,0,buffer.length - 3,"GBK");
                    Log.d(TAG,"a:" + a);
//                    byte[] gbks = "你好".getBytes("GBK");
//                    for (byte gbk : gbks) {
//                        Log.d(TAG,"gbk:" + gbk);
//                    }
//                    String[] chars = a.split(" ");
//                    String str = "";
//                    for(int i = 0; i<chars.length;i++){
//                        str += (char)Integer.parseInt(chars[i]);
//                    }
                    //Log.d(TAG,"str:" + str);
                    ((Activity)mContext).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //将收到的数据显示在TextView上
                            mToast.showToast(a);
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
